#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>	
#include <fcntl.h>
#include <unistd.h>
#include <wait.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <resolv.h>
#include <arpa/nameser.h>
#include <sys/mman.h>
#include <errno.h>
#include <setjmp.h>
#include <time.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>

#define SERV_NAME1 "L1.zmvideo.net"
static int runflag = 1;
static void sig_handle(int signo)
{
	if(signo==SIGINT)
		runflag = 0;
}

static int gethostbyname_proc(const char *name)
{
	struct hostent *host = NULL;
	char **pptr;
	char str[32];

	res_init(); /* read resolv.conf */
	host = gethostbyname(name);
	if(host==NULL)
	{
		fprintf(stderr,"gethostbyname fail for host %s:%s\n",name,hstrerror(h_errno));
		res_close();
		return -1;
	}
	else
	{
		fprintf(stdout,"official hostname: %s\n",host->h_name);
		for(pptr=host->h_aliases;*pptr!=NULL;pptr++)
			fprintf(stdout,"\talias: %s\n",*pptr);
		switch(host->h_addrtype)
		{
			case AF_INET:
				pptr = host->h_addr_list;
				for(;*pptr!=NULL;pptr++)
					fprintf(stdout,"\taddress: %s\n",inet_ntop(host->h_addrtype,*pptr,str,sizeof(str)));
				break;
			default:
				fprintf(stderr,"unknown address type\n");
				break;
		}
	}
	res_close();
	return 0;
}

static int getaddrinfo_proc(const char *name,const char *serv)
{
	struct addrinfo hints, *res;
	int ret = 0;

	memset(&hints,0,sizeof(hints));
	hints.ai_flags = AI_CANONNAME;
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_DGRAM;

	res_init();
	ret = getaddrinfo(name,serv,&hints,&res);
	if(ret)
	{
		fprintf(stderr,"getaddrinfo fail for host %s:%s\n",name,gai_strerror(ret));
		if(ret == EAI_SYSTEM)
		{
			fprintf(stderr,"error:%s\n",strerror(errno));
		}
		res_close();
		return -1;
	}
	else
	{
		struct addrinfo *ptr;
		struct sockaddr_in *servaddr;
		char str[32]={0};

		fprintf(stdout,"canonname : %s\n",res->ai_canonname);
		for(ptr=res;ptr;ptr=ptr->ai_next)
		{
			servaddr = (struct sockaddr_in*)ptr->ai_addr;
			fprintf(stdout,"\taddress: %s\n",
					inet_ntop(ptr->ai_family,&servaddr->sin_addr,str,sizeof(str)));
		}
		freeaddrinfo(res);
	}
	res_close();
	return 0;
}

int main(int argc, char *argv[])
{
	signal(SIGINT,sig_handle);

	//while(runflag)
	{
		if(gethostbyname_proc(SERV_NAME1)<0)
			getaddrinfo_proc(SERV_NAME1,"6001");
		sleep(2);
	}
	return 0;
}

